﻿using System;
using System.Text;
using System.Threading;
using System.IO;
using System.Net;
using System.Security;
using System.Collections.Specialized;
using System.Windows.Forms;

namespace ImageDownloadClient
{
/*    class DownloadThread
    {
        LogAppend WritelnLog;
        public enum DownloadStatus { STATUS_STOP, STATUS_PAUSE, STATUS_WORKING };
        private static Object lockobj = new Object();

        public DownloadThread(LogAppend la, DownloadLog downloadLog,
                              DownloadController controller)
        {
            m_downloadLog       = downloadLog;
            m_controller        = controller;
            WritelnLog = la;

            // 初始化状态，创建线程入口
            m_bDownloading      = false;
            m_DownloadStatus    = DownloadStatus.STATUS_STOP;
            m_entryPoint = new ThreadStart(threadProc);
        }

        public void start()
        {
            m_DownloadStatus    = DownloadStatus.STATUS_WORKING;

            // 创建线程，并设为背景线程，当主线程退出，背景线程也会退出
            m_workThread = new Thread(m_entryPoint);
            m_workThread.IsBackground = true;
            m_workThread.Start();
        }

        // 不应该被执行
        public void pause()
        {
            m_DownloadStatus = DownloadStatus.STATUS_PAUSE;
        }

        // 不应该被执行，使用abort()
        public void stop()
        {
            // 设置为STATUS_STOP并不能保证当前就已
            // 经停止了，所以后面需要等待真正退出
            m_DownloadStatus = DownloadStatus.STATUS_STOP;

            // 等待直到真正退出才返回
            while (m_bDownloading)
                Thread.Sleep(100);
        }

        // 不应该被执行
        public void resume()
        {
            m_DownloadStatus = DownloadStatus.STATUS_WORKING;
        }

        public void abort()
        {
            m_workThread.Abort();

            // 强制退出可能导致m_fileWriter没有得到
            // 正确关闭，所以手动关闭它
            if (m_fileWriter != null)
            {
                m_fileWriter.Close();
            }

            // 复原状态位
            m_DownloadStatus = DownloadStatus.STATUS_STOP;
            m_bDownloading = false;

            // 清理当前下载文件的信息
            resetDownloadInfo();
        }

        private void resetDownloadInfo()
        {
            m_curFileName       = "";
            m_curFileSize       = 0;
            m_curFinishedSize   = 0;
        }

        //使用简单的断点续传手法下载文件
        private long downloadFile(String url, String fileName, String destDir)
        {
            Stream reader=null;
            try
            {                
                m_curFileName           = fileName;

                // 创建文件夹
                if (!Directory.Exists(destDir))
                {
                    Directory.CreateDirectory(destDir);
                }
                //打开上次下载的文件或新建文件 
                long lStartPos = 0;
                if (System.IO.File.Exists(fileName))
                {
                    m_fileWriter = System.IO.File.OpenWrite(destDir + "\\" + fileName);
                    lStartPos = m_fileWriter.Length;
                    m_fileWriter.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针 
                }
                else
                {
                    m_fileWriter = new System.IO.FileStream(fileName, System.IO.FileMode.Create, FileAccess.Write);
                    lStartPos = 0;
                }



                //打开网络连接 
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(url));
                request.Timeout = 15000;
                WebResponse response = request.GetResponse();

                long fileLength = response.ContentLength;

                if (lStartPos < fileLength)
                {
                    if (lStartPos > 0)
                        request.AddRange((int)lStartPos); //设置Range值 

                    //向服务器请求，获得服务器回应数据流 
                    reader = response.GetResponseStream();
                    m_curFileSize = response.ContentLength;    // 得到当前文件大小，如为-1表示ContentLength Header没有使用


                    byte[] buff = new byte[1048576];
                    int justRead = 0;                         // 刚读取的字节数
                    FinishedSize = 0;                         // 至今读取的字节数
                    while ((justRead = reader.Read(buff, 0, buff.Length)) > 0)
                    {
                        m_fileWriter.Write(buff, 0, justRead);
                        FinishedSize += justRead;
                    }
                    m_fileWriter.Close();
                    reader.Close();
                }

                //返回已读字节数
                WritelnLog("Done..."  + FinishedSize + " bytes Readed...");
                return FinishedSize;
            }
            catch (System.Exception ex)
            {
                if(reader != null) reader.Close();
                if(m_fileWriter != null) m_fileWriter.Close();
                WritelnLog("Error occurs!" + FinishedSize + " bytes Readed...");
                WritelnLog(ex.Message);
                return -1;
            }
        }

        public DownloadStatus getCurStatus()
        {
            return m_DownloadStatus;
        }

        public bool isDownloading()
        {
            return m_bDownloading;
        }

        // 从ImageInfo队列中取出imageInfo并下载
        private void threadProc()
        {
            while (m_DownloadStatus != DownloadStatus.STATUS_STOP)
            {
                switch (m_DownloadStatus)
                {
                    case DownloadStatus.STATUS_WORKING:
                    {
                        
                        m_bDownloading = true;
                        long nSize = -1;
                        try
                        {
                            // 下载网页
                            //String htmlName = m_controller.CurrentConcept + "_" + String.Format("{0:D7}", id) + ".jpg.html";
                            //long nSize = downloadFile(imageInfo.ImageRef, htmlName, m_controller.CurrentConceptFolder);
                            WritelnLog("Requesting for the 1st time...");
                            nSize = downloadFile("http://ime.sogou.com/dl/sogou_pinyin_431d.exe", "sogou_pinyin_431d.exe", "F:\\TEST");
                            

                            //请求不成功，重传
                            int repeat = 0;

                            while (nSize == -1 && repeat < 20)
                            {
                                repeat++;
                                Thread.Sleep(100);
                                //nSize = downloadFile(imageInfo.ImageRef, htmlName, m_controller.CurrentConceptFolder);
                                WritelnLog("Requesting for the "+(repeat+1)+"th time...");
                                nSize = downloadFile("http://ime.sogou.com/dl/sogou_pinyin_431d.exe", "sogou_pinyin_431d.exe", "F:\\TEST");
                            }
                        }
                        catch(Exception ex)
                        {
                            // 下载错误，不理它，下一个
                            WritelnLog(ex.Message);
                        }
                        m_bDownloading = false;
                        if (nSize != -1) return;
                        else break;
                    }
                    case DownloadStatus.STATUS_PAUSE:
                    {
                        // 不做任何事情
                        //WritelnLog("Download Pause...");
                        break;
                    }
                }

                // 防止循环过快
                Thread.Sleep(20);
            }
            // DownloadStatus.STATUS_STOP，退出线程
            WritelnLog("Download OK...");
        }

        private String m_curFileName;
        public String FileName
        {
            get { return m_curFileName; }
        }

        private long m_curFileSize;
        public long FileSize
        {
            get { return m_curFileSize; }
        }

        private long m_curFinishedSize;
        public long FinishedSize
        {
            get { return m_curFinishedSize; }
            set { m_curFinishedSize = value; }
        }

        FileStream m_fileWriter;
        public FileStream FileWriter
        {
            get { return m_fileWriter; }
        }

        private DownloadLog         m_downloadLog;
        private DownloadStatus      m_DownloadStatus;
        private ThreadStart         m_entryPoint;
        private Thread              m_workThread;
        private bool                m_bDownloading;
        private DownloadController  m_controller;
    }*/
}